# -*- coding: utf-8 -*-
import web;
import errconst;
import chaosdb;
import recommendconst;
import json;
import model;
import event;
import time,contact2;

class Recommend:
    def POST(self):
        input = web.input();
        if(hasattr(input, 'op')):
            op = input.op;
            if(op == "s" or op == "ss"):
                jsonObj = web.input().json;
                obj = json.loads(jsonObj);
                #only the sender and receiver are both active, the recommendation is stored in db
                destUser = model.getUser(obj["destUID"]);
                if(op == "s"):
                    sourceUser = model.getUser(obj["sourceUID"]);
                    rItem = RecommendInfo(obj["trackInfo"],int(obj["sourceUID"]),int(obj["destUID"]));
                    if(destUser!=None and sourceUser!=None):
                        rid = model.addNewRecommendation(rItem);
                        return rid;
                elif(op=="ss"):
                    destUIDs = obj["destUIDs"];
                    for did in destUIDs:
                        destUser = model.getUser(int(did));
                        if(destUser==None):
                            inviteItem=chaosdb.getInviteItem(int(obj["sourceUID"]),did);
                            if(inviteItem==None):
                                return errconst.RECOMMEND_RID_ERR;
                            else:
                                pass;
                    rItem = RecommendInfo(obj["trackInfo"],int(obj["sourceUID"]),-1);
                    rids = model.addNewRes(rItem, destUIDs);
#                    print rids;
                    return rids;
            else:
                ops = input.op.split("|");
                rids = input.rid.split("|");
            
                if(len(ops)!=len(rids)):
                    return errconst.RECOMMEND_RID_ERR;
                else:
                    for i in range(len(ops)):
                        op = ops[i];
                        rid = int(rids[i]);
                        reponseToRecommends(rid,op)
        else:
            return errconst.RECOMMEND_WITHOUT_OP_CODE;
        
        
    
    def GET(self):
        input = web.input();
        if(hasattr(input, 'uid')):
            if(hasattr(input, 'op')):
                op = input.op;
                if(op=="re"):
                    rIdStr = input.rids;
                    rIds = str(rIdStr).split('|');
                    list = chaosdb.getResponedInSourceId(int(input.uid),rIds);
                    return json.dumps({'sourceid':int(input.uid),'rst':json.dumps(list)})
                elif(op=="like"):
                    return getLatestLikeRecommend(input,int(input.uid))
                elif(op=="stat"):
                    id = int(input.uid)
                    if(hasattr(input, "cpid")):
                        cpid = int(input.cpid)
                        return json.dumps(getRecommedStatistics(id, cpid))
            else:
                raise web.seeother('/?uid=%s'%web.input().uid);
        else:
            return errconst.GET_RECOMMEND_LIST_WITHOUT_UID;

def getLatestLikeRecommend(input,uid):
    if(hasattr(input, "destIds")):
        destIds = str(input.destIds).split("|")
        if(len(destIds)>0 and len(destIds)<=contact2.CONTACTS_MAX):
            rst = {};
            for destID in destIds:
                if(destID==''):
                    break
                recommend = chaosdb.getRecentLikeRecommend(uid, int(destID))
                if(recommend!=None):
                    songid = recommend.songid;
                    song = chaosdb.getTrack(songid);
                    if(song!=None):
                        songJson = json.dumps(song)
                        rst[int(destID)] = {"time":time.mktime(recommend.time.timetuple()),"song":songJson}
                    else:
                        rst[int(destID)] = None;
                else:
                    rst[int(destID)] = None;
                    
            return json.dumps(rst);
        else:
            return errconst.EXCEED_MAX_RECENT_LIKE_RECOMMENDS;
    else:
        return errconst.GET_RECENT_RECOMMEND_ITEM_WITHOUT_DESTIDS;
    
def getRecommedStatistics(id,cpId):
    total = chaosdb.getRecommendTotal(id, cpId)
    like  = chaosdb.getRecommendLikeCount(id, cpId)
    return {"total":total["COUNT(*)"],"like":like["COUNT(*)"],"destid":id,"sourceid":cpId}
    
class RecommendInfo:
    
    def __init__(self,infoDic,sourceUID,destUID):
        self.destUID = destUID;
        self.sourceUID = sourceUID;
        self.info = infoDic;
        
def reponseToRecommends(rid,op):
    if(op == "l"):
        #like the recommendation
        chaosdb.setReItemFlag(rid,recommendconst.LIKED);
        reItem = chaosdb.getRecommendation(rid);
        songItem = chaosdb.getTrack(reItem.songid);
        destUser = model.getUser(reItem.destid);
        if(reItem!=None and songItem!=None and destUser!=None):
            event.addEvent(reItem.sourceid,event.TYPE_RESPONSE_RE,
                           "[type=user,id=%d,display=%s]喜欢你推荐的[type=track,sid=%d,display=%s]"%(reItem.destid,destUser.name,reItem.songid,songItem.name));
            return 1;
    elif(op == "b"):
    #ban the recommendation
        chaosdb.setReItemFlag(rid,recommendconst.BANED);
        return 1;
    elif(op == "p"):
    #pass the recommendation
        chaosdb.setReItemFlag(rid,recommendconst.SKIPED);
        return 1;
    elif(op == "invalid"):
        chaosdb.setReItemFlag(rid,recommendconst.INVALID);
        return 1;
